<?php

/**
 * Handle file uploads via XMLHttpRequest
 */
 
//ajax文件上传操作

class qqUploadedFileXhr {
	//@var file filed name 
	var $filed_name;
	
	//fenghao 2013-04-02 edit this 
	function __construct($_files = 'qqfile'){
		
		$this->filed_name = $_files;
	
	}

	/**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    function save($path) {    
        $input = fopen("php://input", "r");
        $temp = tmpfile();
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);
        
        if ($realSize != $this->getSize()){            
            return false;
        }
        
        $target = fopen($path, "w");        
        fseek($temp, 0, SEEK_SET);
        stream_copy_to_stream($temp, $target);
        fclose($target);
        
        return true;
    }
    function getName() {
        return $_GET[$this->filed_name];
    }
    function getSize() {
        if (isset($_SERVER["CONTENT_LENGTH"])){
            return (int)$_SERVER["CONTENT_LENGTH"];            
        } else {
            throw new MC_Exception('Getting content length is not supported.');
        }      
    }   
}

/**
 * Handle file uploads via regular form post (uses the $_FILES array)
 */
class qqUploadedFileForm {  

	//@var file filed name 
	var $filed_name;
	
	//fenghao 2013-04-02 edit this 
	function __construct($_files = 'qqfile'){
		
		$this->filed_name = $_files;
	
	}

    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    function save($path) {
        if(!move_uploaded_file($_FILES[$this->filed_name]['tmp_name'], $path)){
            return false;
        }
        return true;
    }
    function getName() {
        return $_FILES[$this->filed_name]['name'];
    }
    function getSize() {
        return $_FILES[$this->filed_name]['size'];
    }
}

class qqFileUploader {
    private $allowedExtensions = array();
    private $sizeLimit = 10485760;
    private $file;

    function __construct($_files = 'qqfile', array $allowedExtensions = array(), $sizeLimit = 10485760){        
        $allowedExtensions = array_map("strtolower", $allowedExtensions);
            
        $this->allowedExtensions = $allowedExtensions;        
        $this->sizeLimit = $sizeLimit;
        
        $this->checkServerSettings();       

        if (isset($_GET[$_files])) {
            $this->file = new qqUploadedFileXhr($_files);
        } elseif (isset($_FILES[$_files])) {
            $this->file = new qqUploadedFileForm($_files);
        } else {
            $this->file = false; 
        }
    }
    
    private function checkServerSettings(){        
        $postSize = $this->toBytes(ini_get('post_max_size'));
        $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));        
        
        if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
            $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';             
            //die("{'error':'increase post_max_size and upload_max_filesize to $size'}");  
			return array('error' => -1, 'msg'=>"上传文件大小超过限($size)制，请压缩后再试。");
        }        
    }
    
    private function toBytes($str){
        $val = trim($str);
        $last = strtolower($str[strlen($str)-1]);
        switch($last) {
            case 'g': $val *= 1024;
            case 'm': $val *= 1024;
            case 'k': $val *= 1024;        
        }
        return $val;
    }
    
    /**
     * Returns array('success'=>true) or array('error'=>'error message')
     */
    function handleUpload($uploadDirectory, $nameFormat=NULL, $replaceOldFile = FALSE){
        if (!is_writable($uploadDirectory)){
			$err = "服务器错误：上传目录不可写入";
			//throw new MC_Exception($err);
            return array('error' =>-1, "msg"=>$err);
        }
        
        if (!$this->file){
 			$err = "文件上传失败";
			//throw new MC_Exception($err);
            return array('error' =>-1, "msg"=>$err);
        }
        
        $size = $this->file->getSize();
        
        if ($size == 0) {
 			$err = "文件容量为空";
			//throw new MC_Exception($err);
            return array('error' =>-1, "msg"=>$err);
        }
        
        if ($size > $this->sizeLimit) {
 			$err = "文件容量超过限制（".($this->sizeLimit / 1024 / 1024)."M），请重试";
			//throw new MC_Exception($err);
            return array('error' =>-1, "msg"=>$err);
        }
        
        $pathinfo = pathinfo($this->file->getName());
		//文件名使用以下规则 md5(filename+time())
        //$filename = $pathinfo['filename'];
		if($nameFormat == "uuid"){
			$filename = StringFuncs::keyGen();
		}else if($nameFormat == 'md5'){
	        $filename = md5($pathinfo['filename']+time());
		}else if($nameFormat != NULL){
	        $filename = call_user_func($nameFormat, $pathinfo['filename']);
		}else{
			$filename = $pathinfo['filename'];
		}
        //$filename = md5(uniqid());
        $ext = $pathinfo['extension'];

        if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
            $these = implode(', ', $this->allowedExtensions);
 			$err = "文件类型不符合要求，请使用如下类型文件". $these;
			//throw new MC_Exception($err);
            return array('error' =>-1, "msg"=>$err);
            //return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
        }
        
        if(!$replaceOldFile){
            /// don't overwrite previous files that were uploaded
            while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
                $filename .= rand(10, 99);
            }
        }
        
        $filepath = $uploadDirectory . $filename . '.' . $ext;
		if ($this->file->save($filepath)){
			//$filepath = str_replace(ROOT_DIR, ".", $filepath);
            return array('success'=>true, 'file'=>$filepath);
        } else {
 			$err = "无法保存上传文件，上传操作被用户取消或服务器错误";
			//throw new MC_Exception($err);
            return array('error' => $err);
            //return array('error'=> 'Could not save uploaded file.' .
            //    'The upload was cancelled, or server error encountered');
        }
        
    }    
}
